#include "ChatServer.h"
#include <iostream>

ChatServer::ChatServer(int port)
    : networkModule(port)
{
}

bool ChatServer::start()
{
    // 设置回调
    networkModule.setMessageCallback([this](int clientSocket, const string &message)
                                     { handleClientMessage(clientSocket, message); });

    networkModule.setDisconnectCallback([this](int clientSocket)
                                        { handleClientDisconnect(clientSocket); });

    // 启动网络模块
    return networkModule.start();
}

void ChatServer::stop()
{
    networkModule.stop();
}

void ChatServer::handleClientMessage(int clientSocket, const string &message)
{
    auto msg = MessageHandler::parseMessage(message);

    switch (msg.type)
    {
    case MessageHandler::LOGIN:
        handleLogin(clientSocket, msg);
        break;
    case MessageHandler::LOGOUT:
        handleLogout(clientSocket, msg);
        break;
    case MessageHandler::PRIVATE_MSG:
        handlePrivateMessage(clientSocket, msg);
        break;
    case MessageHandler::BROADCAST_MSG:
        handleBroadcastMessage(clientSocket, msg);
        break;
    case MessageHandler::ERROR:
        sendError(clientSocket, "Invalid message format");
        break;
    }
}

void ChatServer::handleLogin(int clientSocket, const MessageHandler::Message &msg)
{
    userManager.addUser(clientSocket, msg.sender);
    string response = MessageHandler::formatMessage(
        MessageHandler::LOGIN, "SERVER", msg.sender, "Login successful");
    networkModule.sendMessage(clientSocket, response);

    // 向所有用户广播新用户登录
    broadcastMessage("SERVER", msg.sender + " has joined the chat");
}

void ChatServer::handleLogout(int clientSocket, const MessageHandler::Message &msg)
{
    shared_ptr<User> user = userManager.getUser(clientSocket);
    if (user)
    {
        string username = user->getUsername();
        userManager.removeUser(clientSocket);

        // 向所有用户广播用户退出
        broadcastMessage("SERVER", username + " has left the chat");
    }
}

void ChatServer::handlePrivateMessage(int clientSocket, const MessageHandler::Message &msg)
{
    shared_ptr<User> sender = userManager.getUser(clientSocket);
    if (!sender)
    {
        sendError(clientSocket, "Not logged in");
        return;
    }

    // 查找接收者
    for (auto user : userManager.getAllUsers())
    {
        if (user->getUsername() == msg.receiver)
        {
            string response = MessageHandler::formatMessage(
                MessageHandler::PRIVATE_MSG, sender->getUsername(),
                msg.receiver, msg.content);
            networkModule.sendMessage(user->getSocket(), response);
            return;
        }
    }

    // 未找到接收者
    sendError(clientSocket, "User not found: " + msg.receiver);
}

void ChatServer::handleBroadcastMessage(int clientSocket, const MessageHandler::Message &msg)
{
    shared_ptr<User> sender = userManager.getUser(clientSocket);
    if (!sender)
    {
        sendError(clientSocket, "Not logged in");
        return;
    }

    broadcastMessage(sender->getUsername(), msg.content);
}

void ChatServer::handleClientDisconnect(int clientSocket)
{
    shared_ptr<User> user = userManager.getUser(clientSocket);
    if (user)
    {
        string username = user->getUsername();
        userManager.removeUser(clientSocket);

        // 向所有用户广播用户退出
        broadcastMessage("SERVER", username + " has left the chat");
    }
}

void ChatServer::broadcastMessage(const string &sender, const string &content)
{
    string message = MessageHandler::formatMessage(
        MessageHandler::BROADCAST_MSG, sender, "", content);

    for (auto user : userManager.getAllUsers())
    {
        networkModule.sendMessage(user->getSocket(), message);
    }
}

void ChatServer::sendError(int clientSocket, const string &errorMsg)
{
    string message = MessageHandler::formatMessage(
        MessageHandler::ERROR, "SERVER", "", errorMsg);
    networkModule.sendMessage(clientSocket, message);
}